/**
 * Created by liuqingling on 16/11/16.
 */
/**
 * Created by xiaoz on 16/8/13.
 */

define(["utils", "base"], function (utils, baseClass) {var data = {
        "code": 0,
        "level": 0,
        "msg": "成功",
        "data": {
            "body": [
                {
                    "size": 0,
                    "description": "请输入",
                    "id": "1479204389541",
                    "title": "文本输入框",
                    "isRequired": "0",
                    "value": "",
                    "content": "222",
                    "type": "InputText"
                },
                {
                    "type": "InputTextNum",
                    "description": "请输入",
                    "unit": "元",
                    "size": 0,
                    "id": "1479204405579",
                    "title": "数字输入框",
                    "isRequired": "0",
                    "value": "",
                    "content": "111"
                },
                {
                    "options": [
                        {
                            "string": "选项1"
                        },
                        {
                            "string": "选项2"
                        },
                        {
                            "string": "选项3"
                        }
                    ],
                    "type": "InputCheckbox",
                    "id": "1479204407206",
                    "title": "复选框",
                    "isRequired": "1",
                    "value": "",
                    "content": "选项1;选项2"
                },
                {
                    "options": [
                        {
                            "string": "选项1"
                        },
                        {
                            "string": "选项2"
                        },
                        {
                            "string": "选项3"
                        }
                    ],
                    "checked": 0,
                    "type": "InputRadio",
                    "id": "1479204408953",
                    "title": "单选框",
                    "isRequired": "1",
                    "value": "",
                    "content": "选项3"
                },
                {
                    "dateType": "1",
                    "type": "InputDate",
                    "id": "1479204410668",
                    "title": "日期",
                    "isRequired": "1",
                    "value": "",
                    "content": "2016-11-23"
                },
                {
                    "dateType": "1",
                    "type": "InputDate",
                    "id": "1479204410669",
                    "title": "end日期",
                    "isRequired": "1",
                    "value": "",
                    "content": ""
                }
            ],
            "title": "全类型",
            "description": "请输入",
            "files": [],
            "id": 15957,
            "type": 1,
            "created": 1479204762,
            "cmid": 2399974,
            "icon": "",
            "type_name": "日报"
        }
    };


    function InputText(config) {
        this.itemData = config.itemData;
        this.rootInstance = config.rootInstance;
        var required = this.itemData.isRequired == 1 ? "required" : '';
        var placeholder = this.itemData.description||(this.itemData.size == 0 ? "请输入" : "不超过" + this.itemData.size + "  个字");
        this.$el = $("<div class='row' id='" + this.itemData.id + "'></div>");
        var label = $('<label class="' + required + '">' + this.itemData.title + '</label>');
        this.textArea = $('<textarea placeholder="' + placeholder + '">' + this.itemData.content + '</textarea>');
        this.$el.append(label).append(this.textArea);
    }


    InputText.prototype = {
        getValue: function () {
            this.itemData.value = this.textArea.val().trim();
            this.itemData.content = this.textArea.val().trim();
            return this.itemData;
        },
        validate: function () {
          var value = this.textArea.val().trim();
            if (this.itemData.isRequired == 0||(this.itemData.isRequired == 1 &&value.length>0)) {
                return true;
            }
            this.rootInstance.pageview.showTip({
                text:this.itemData.title+"此项为必填"
            });
            return false;
        },
        setValue: function (val) {
            this.textArea.val(val);
        }
    }


    function InputDate(config) {
        this.itemData = config.itemData;
        var _this = this;
        this.rootInstance = config.rootInstance;
        var required = this.itemData.isRequired == 1 ? "required" : '';
        this.$el = $("<div class='row' id='" + this.itemData.id + "'></div>");
        var label = $('<label class="' + required + '">' + this.itemData.title + '</label>');
        var dateWrap = $('<div class="icon-date"></div>');
        //this.value = this.itemData.content;
        this.input = $('<input type="text" placeholder="请选择日期" value="' + (this.itemData.value?this.itemData.value:utils.ConvertDateToStr(new Date(),'yy-MM-dd')) + '" disabled/>');
        dateWrap.append(this.input);
        this.$el.append(label).append(dateWrap);
        dateWrap.bind("click", function (e) {
            _this.rootInstance.showCanendar(e, _this);
        });
    }

    InputDate.prototype = {
        getValue: function () {
            this.itemData.content = this.input.val().trim();
            this.itemData.value = this.input.val().trim();
            return this.itemData;
        },
        validate: function () {
          var value = this.input.val();
            if (this.itemData.isRequired == 0||(this.itemData.isRequired == 1 && value.length>0)) {
                return true;
            }
            this.rootInstance.pageview.showTip({
                text:this.itemData.title+"此项为必填"
            });
            return false;
        },
        setValue: function (val) {
            this.input.val(val);
        }
    }


    function CheckBox (config){
      var _this = this;
      this.itemData = config.itemData;
      this.parent = config.parent;
      this.label  =this.itemData.string;
      this.index = config.index;
      this.$el = $('<div class="checkbox-item"></div>');
      var checkBoxLabel = $('<label>' + this.itemData.string + '</label>');
      this.$el.append(checkBoxLabel);
      this.$el.bind("click",function(e){
        _this.parent.itemSelected(_this);
      });
    }

    CheckBox.prototype = {
      selected:function(){
        var index = this.parent.selectedItems.indexOf(this);
        if(index>=0){
          this.unSelected();
          return;
        }
        this.$el.addClass("checked");
        this.parent.selectedItems.push(this);
      },
      unSelected:function(){
        var index = this.parent.selectedItems.indexOf(this);
        if(index>=0){
          this.parent.selectedItems.splice(index,1);
        }
        this.$el.removeClass("checked");
      }

    }


    function InputCheckbox(config) {
        this.itemData = config.itemData;
        this.rootInstance = config.rootInstance;
        var required = this.itemData.isRequired == 1 ? "required" : '';
        this.$el = $("<div class='row' id='" + this.itemData.id + "'></div>");
        var label = $('<label class="' + required + '">' + this.itemData.title + '</label>');
        var checkboxWrap = $('<div class="checkbox-wraper"></div>');
        this.selectedItems = [];
        this.checkBoxs = [];

        for (var j = 0; j < this.itemData.options.length; j++) {
            var ci = new CheckBox({
              itemData:this.itemData.options[j],
              parent:this,
              index:j
            });
            this.checkBoxs.push(ci);
            checkboxWrap.append(ci.$el);
        }
        this.$el.append(label).append(checkboxWrap);
        this.setValue(this.itemData.value);
    }

    InputCheckbox.prototype = {
        itemSelected:function(itemInstance){
          itemInstance.selected();
        },
        getValue: function () {
            var content = [];
            var indexArr = [];
            for(var i=0,j=this.selectedItems.length;i<j;i++){
              var item  =this.selectedItems[i];
              content.push(item.label);
              indexArr.push(item.index);
            }
            this.itemData.content = content.join(';');
            this.itemData.value = indexArr.join(',');
            return this.itemData;
        },
        validate: function () {
            if (this.itemData.isRequired == 0||(this.itemData.isRequired == 1 && this.getValue().content.length>0)) {
                return true;
            }
            this.rootInstance.pageview.showTip({
                text:this.itemData.title+"此项为必选"
            });
            return false;
        },
        setValue: function (val) {
          var valArr = val.split(",");
          for(var i=0,j=valArr.length;i<j;i++){
            var index = valArr[i];
            for(var ii = 0,jj=this.checkBoxs.length;ii<jj;ii++){
              if(this.checkBoxs[ii].index.toString()===index){
                this.checkBoxs[ii].selected();
              }
            }
          }
        }
    }


    function RadioItem(config){
      var _this = this;
      this.index = config.index;
      var itemData = config.itemData;
      this.parent = config.parent;
      this.$el = $('<div class="radio-item"></div>');
      this.label = itemData.string ;
      var radioLabel = $('<label>' +this.label + '</label>');
      this.$el.append(radioLabel);
      this.$el.bind("click",function(){
        _this.parent.itemSelected(_this);
      });
    }
    RadioItem.prototype = {
      selected:function(){
        if(this.parent.selectedItem){
          this.parent.selectedItem.unSelected();
        }
        this.parent.selectedItem = this;
        this.$el.addClass("checked");
      },
      unSelected:function(){
        this.$el.removeClass("checked");
      }

    }

    function InputRadio(config) {

        this.itemData = config.itemData;
        this.rootInstance = config.rootInstance;
        var required = this.itemData.isRequired == 1 ? "required" : '';

        this.$el = $("<div class='row' id='" + this.itemData.id + "'></div>");
        var label = $('<label class="' + required + '">' + this.itemData.title + '</label>');
        var radioWrapper = $('<div class="radio-wraper"></div>');

        this.radios = [];
        var needSelected='';
        for (var k = 0; k < this.itemData.options.length; k++) {
            var ri = new RadioItem({
              parent:this,
              index:k,
              itemData:this.itemData.options[k]
            });
            radioWrapper.append(ri.$el);
            this.radios.push(ri);
        }
        this.radios[0].selected();
        this.$el.append(label).append(radioWrapper);

        this.setValue(this.itemData.value);
    }

    InputRadio.prototype = {
      itemSelected:function(itemInstance){
        itemInstance.selected();
      },
        getValue: function () {
            this.itemData.content = this.selectedItem.label;
            this.itemData.value = this.selectedItem.index;
            return this.itemData;
        },
        validate: function () {
            return true;
        },
        setValue: function (val) {

            try{
              val = parseInt(val);
              val = isNaN(val)?0:val;
            }catch(e){
              val = 0;
            }
            if(val>this.radios.length-1){
              val = 0;
            }
            this.radios[val].selected();

        }
    }

    function InputTextNum(config) {

        this.itemData = config.itemData;
        this.rootInstance = config.rootInstance;

        var required = this.itemData.isRequired == 1 ? "required" : '';
        this.$el = $("<div class='row' id='" + this.itemData.id + "'></div>");
        var label = $('<label class="' + required + '">' + this.itemData.title + '</label>');
        var numWrapper = $('<div class="icon-number"></div>');
        this.input = $('<input type="number" value="'+this.itemData.value+'" placeholder="请输入数字(单位:' + this.itemData.unit + ')"/>')
        numWrapper.append(this.input);
        this.$el.append(label).append(numWrapper);
    }

    InputTextNum.prototype = {
        getValue: function () {
            this.itemData.content = this.input.val().trim();
            if(this.itemData.unit){
              this.itemData.content+= ""+this.itemData.unit;
            }
            this.itemData.value = this.input.val().trim();
            return this.itemData;
        },
        validate: function () {
          var value = this.input.val().trim();
          if(isNaN(value)){
            this.rootInstance.pageview.showTip({
                text:this.itemData.title+"此项必须为数字"
            });
            return;

          }
            if (this.itemData.isRequired == 0||(this.itemData.isRequired == 1 && value.length>0)) {
                return true;
            }

            this.rootInstance.pageview.showTip({
                text:this.itemData.title+"此项为必填"
            });
            return false;
        },
        setValue: function (val) {
            this.input.val(val);
        }
    }

    var Component = function (config) {
        var _this = this;
        config.style = config.style || {};
        Component.baseConstructor.call(this, config);
        var showCanendarMethodName = this.config.comKey + "_showcanledar";
        this.showCanendarMethod = this.pageview.plugin[showCanendarMethodName];

    }
    utils.extendClass(Component, baseClass);
    Component.prototype.getValue = function () {
        var re = [];
        for (var id in this.itemsDict) {
            var item = this.itemsDict[id];
            var itemRe = {};
            if(!item.validate()){
                return null;
            }
            re.push(item.getValue());
        }
        return re;
    };
    Component.prototype.showCanendar = function (e, itemInstance) {
        this.showCanendarMethod.call(this.pageview.plugin, this, {
            e: e,
            itemInstance: itemInstance
        });
    },
        Component.prototype.createLayout = function (data) {
            this.itemsDict = {};
            var tpls = '';
            data = data||[];
            for (var i = 0; i < data.length; i++) {
                var itemData = data[i];
                var item;
                var type = itemData.type;
                if(!itemData.id){
                    continue;
                }
                var id = itemData.id.toString();
                var required = itemData.isRequired == 1 ? "required" : '';
                if (type == "InputText") {
                    item = new InputText({itemData: itemData, rootInstance: this});


                } else if (type == "InputDate") {
                    item = new InputDate({itemData: itemData, rootInstance: this});

                } else if (type == "InputCheckbox") {

                    item = new InputCheckbox({itemData: itemData, rootInstance: this});

                } else if (type == "InputRadio") {
                    item = new InputRadio({itemData: itemData, rootInstance: this});

                } else if (type == "InputTextNum") {
                    item = new InputTextNum({itemData: itemData, rootInstance: this});

                }

                item && this.$el.append(item.$el);
                if (item) {
                    this.itemsDict[id] = item;
                }

            }
            this.$el.addClass("dailyrender").append(tpls);
        };

    return Component;
});
